Skip to main content

baseConvert

Type

function

Summary

Converts a number from one base to another.

Syntax

baseConvert(<number>, <originalBase>, <destinationBase>)

Description

Use the baseConvert function to provide input or output of numbers in a base other than base 10: for example, in hexadecimal (base 16) or binary (base 2).

The everyday decimal number system is called "base 10" because we count from 1 to 9, and the tenth digit moves over to the tens place and is written 10: one group of ten, plus zero extra ones. Similarly, a number like 384 means one group of a hundred (10^2), plus eight groups of ten, plus four leftover ones.

It is possible to write numbers in other bases. For example, suppose you want to write the number six in base 4. In base 4, we count from 1 to 3, and the fourth digit moves over to the "fours place". So the numbers from one to six, in base 4, are written "1, 2, 3, 10, 11, 12". The number 12 in base 4 means one group of four, plus two leftover ones. This same number is written as 6 in base 10.

If the base is greater than 10, then digits greater than 9 are expressed as capital letters: A is the digit ten, B is the digit eleven, and so on.

LiveCode always does math in base 10, so if you want to perform mathematical calculations such as addition on a number in another base, you must first convert the number to base 10, do the calculation, then convert back to the original base. Here is an example:

    function hexSum pFirstAddend, pSecondAddend
-- adds together two hexadecimal numbers
put baseConvert(pFirstAddend,16,10) into tConvertedAddend1
put baseConvert(pSecondAddend,16,10) into tConvertedAddend2
put tConvertedAddend1 + tConvertedAddend2 into tBaseTenSum
return baseConvert(tBaseTenSum,10,16)
end hexSum

Parameters

NameTypeDescription

number

The number to be converted, expressed in its original base. The number must be an integer between zero and 4,294,967,295 (2^32 - 1). If the number includes non-digits (as, for example, a base-16 number can include letters A-F), enclose the number in quotes.

originalBase

integer

An integer between 2 and 36.

destinationBase

integer

An integer between 2 and 36.

Examples

baseConvert(16,10,2) -- yields 10000, which is 16 in base 2
baseConvert(27,10,16) -- yields 1B, which is 27 in base 16
baseConvert("1C",16,10) -- yields 28, the base-10 equivalent of 1C

function: exp, URLDecode, format

glossary: binary, hexadecimal, return

operator: bitNot

property: convertOctals

Compatibility and Support

Introduced

LiveCode 1.0

OS

mac

windows

linux

ios

android

Platforms

desktop

server

mobile

Thank you for your feedback!

Was this page helpful?